/**
 * Zhz.net Inc.
 * Copyright (c) 2004-2011 All Rights Reserved.
 */
package com.zhz.lib.cms.manage.imagesmanage;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;

import com.zhz.lib.cms.vo.image.ImageVO;
import com.zhz.project.common.util.alibaba.StringUtil;
import com.zhz.project.common.util.zhzutil.ZhzCommonUtil;
import com.zhz.project.common.util.zhzutil.ZhzHttpRequestUtil;

/**
 *
 * @author Administrator
 * @version $Id: imagesManageAction.java, v 0.1 Dec 6, 2012 11:06:31 AM Administrator Exp $
 */
public class imagesManageAction extends DispatchAction {
    private static Logger logger = Logger.getLogger(imagesManageAction.class);

    private String        picPath;
    private String        linkFilePath;

    /**
     * 显示列表！！
     * 
     * @param mapping
     * @param form
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    public ActionForward imageslist(ActionMapping mapping, ActionForm form,
                                    HttpServletRequest request, HttpServletResponse response)
                                                                                             throws Exception {
        List<String> picsList = new ArrayList<String>();

        List<ImageVO> imageVOList = new ArrayList<ImageVO>();
        Map<String, String> map = PicProperties.readProperties(this.linkFilePath);

        File dirFile = new File(this.getPicPath());
        // 列出源文件夹下所有文件
        File[] files = dirFile.listFiles();
        if (files != null) {
            for (int i = 0; i < files.length; i++) {
                if (files[i].isFile() && !StringUtil.contains(files[i].getName(), "url.properties")) {
                    ImageVO vo = new ImageVO();

                    vo.setName(files[i].getName());
                    vo.setLink(map.get(files[i].getName()));
                    imageVOList.add(vo);
                }
            }
        }

        request.setAttribute("imageVOList", imageVOList);
        request.setAttribute("picPath", this.getPicPath() + "/");

        return mapping.findForward("images-list");
    }

    /**
     * 添加
     * 
     * @param mapping
     * @param form
     * @param request
     * @param response
     * @return
     */
    public ActionForward imagesadd(ActionMapping mapping, ActionForm form,
                                   HttpServletRequest request, HttpServletResponse response) {
        return mapping.findForward("images-add");
    }

    /**
     * 保存
     * 
     * @param mapping
     * @param form
     * @param request
     * @param response
     * @return
     * @throws UnsupportedEncodingException 
     * @throws IOException 
     */
    public ActionForward imagessave(ActionMapping mapping, ActionForm form,
                                    HttpServletRequest request, HttpServletResponse response)
                                                                                             throws UnsupportedEncodingException {
        request.setAttribute("add", "add");

        UploadActionForm uaf = (UploadActionForm) form;

        String filename = new String(uaf.getPicture().getFileName().getBytes(), "utf-8");

        String link = uaf.getLink();

        FileOutputStream fos = null;
        try {
            filename = ZhzCommonUtil.getFileNameWithUnderlineTime(filename);
            fos = new FileOutputStream(this.getPicPath() + "/" + filename);
            fos.write(uaf.getPicture().getFileData());
            fos.flush();
            Map<String, String> map = PicProperties.readProperties(this.linkFilePath);
            map.put(filename, link);
            PicProperties.writeProperties(this.linkFilePath, map);
        } catch (Exception e) {
            logger.error("图片保存失败:" + this.getPicPath() + "/" + uaf.getPicture().getFileName(), e);
            return mapping.findForward("images-result");
        } finally {
            try {
                fos.close();
            } catch (Exception e2) {
                logger.error("图片保存失败:" + this.getPicPath() + "/" + uaf.getPicture().getFileName(),
                    e2);
            }
        }

        request.setAttribute("addresult", "addresult");

        return mapping.findForward("images-result");
    }

    /**
     * 删除链接
     */
    public ActionForward imagesdel(ActionMapping mapping, ActionForm form,
                                   HttpServletRequest request, HttpServletResponse response)
                                                                                            throws Exception {
        String picture = this.getPicPath() + "/" + ZhzHttpRequestUtil.getParameters(request, "pic");
        File file = new File(picture);
        // 如果文件路径对应的文件存在，并且是一个文件，则直接删除。
        if (file.exists() && file.isFile()) {
            if (file.delete()) {

                logger.info("删除单个图片" + picture + "成功！");

                Map<String, String> map = PicProperties.readProperties(this.linkFilePath);
                map.remove(ZhzHttpRequestUtil.getParameters(request, "pic"));
                PicProperties.writeProperties(this.linkFilePath, map);

                request.setAttribute("del", "del");
                request.setAttribute("delResult", "delResult");
            } else {
                logger.error("删除单个图片" + picture + "失败！");
            }
        } else {
            logger.error("删除单个图片失败：" + picture + "文件不存在！");
        }

        /**
         * 返回
         */
        return mapping.findForward("images-result");
    }

    /**
     * Getter method for property <tt>picPath</tt>.
     * 
     * @return property value of picPath
     */
    public String getPicPath() {
        return picPath;
    }

    /**
     * Setter method for property <tt>picPath</tt>.
     * 
     * @param picPath value to be assigned to property picPath
     */
    public void setPicPath(String picPath) {
        this.picPath = picPath;
    }

    public void setLinkFilePath(String linkFilePath) {
        this.linkFilePath = linkFilePath;
    }

}